﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ShareMarking.Systems.Service;
using ShareMarking.Service;
using ShareMarking.Entity;
using MySoft.Data;
using Common.Utilities.Excel.Export;
using System.IO;
using System.Data;
using Common.Utilities.Excel;
using ShareMarking.Interface;
using System.Configuration;
using System.Net;
using System.Drawing.Imaging;

namespace ShareMarking.Web.admin.EnterPrise.QrStore
{
    public partial class Index : ManagePage
    {


        #region 参数配置=================================

        private string httpstr = ConfigurationManager.AppSettings["vigohttp"];
        private string signsecret = ConfigurationManager.AppSettings["signscrect"];

        protected int totalCount;
        protected int page;
        //protected string S_name = string.Empty;
        protected string pageSizeCookieKey = "qr_Store_index_page_size";//当前页的每页大小的cookiekey
        protected int pageSize
        {
            get
            {
                int _default_size = 10;
                int _pagesize;
                if (int.TryParse(Utils.GetCookie(pageSizeCookieKey), out _pagesize))
                {
                    if (_pagesize > 0)
                    {
                        return _pagesize;
                    }
                }
                return _default_size;
            }
        }
        protected string orderBy = "qr_Store.StoreCode desc";

        protected string keywords = string.Empty;
        protected string searchURL { get { return Utils.CombUrlTxt("Index.aspx", "keywords={0}", this.keywords); } }

        #endregion

        #region 初始化===================================

        protected void Page_Load(object sender, EventArgs e)
        {
            //检查权限
            //ChkAdminLevel("user_list", ShareMarkingEnums.ActionEnum.View.ToString());

            //初始化搜索参数
            this.keywords = DTRequest.GetQueryString("keywords");

            if (!Page.IsPostBack)
            {
                //绑定下拉框的值

                //绑定列表
                RptBind();
            }
        }

        #endregion

        #region 绑定下拉框===============================

        #endregion

        #region 绑定列表=================================
        private void RptBind()
        {
            this.page = DTRequest.GetQueryInt("page", 1);

            //获取数据源
            if (!keywords.IsNullOrEmpty())
            {
                this.txtKeywords.Text = keywords;
            }
            this.rptList.DataSource = qr_StoreService.Instance.Get_qr_Store_PageSelect(page, pageSize, orderBy, out totalCount, keywords);
            this.rptList.DataBind();

            //绑定页码
            txtPageNum.Text = this.pageSize.ToString();
            string pageUrl = ComLib.UrlHelper.Instance.SetUrl(searchURL).AddParam("page", "__id__").GetAddedParamUrl();
            PageContent.InnerHtml = Utils.OutPageList(this.pageSize, this.page, this.totalCount, pageUrl, 8);
        }
        #endregion

        #region 搜索操作=================================

        //关健字查询
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            this.keywords = txtKeywords.Text;
            Response.Redirect(searchURL);
        }

        //筛选类别
        //设置分页数量
        protected void txtPageNum_TextChanged(object sender, EventArgs e)
        {
            int _pagesize;
            if (int.TryParse(txtPageNum.Text.Trim(), out _pagesize))
            {
                if (_pagesize > 0)
                {
                    Utils.WriteCookie(pageSizeCookieKey, _pagesize.ToString(), 14400);
                }
            }
            Response.Redirect(searchURL);
        }

        protected void btnDetailedSearch_Click(object sender, EventArgs e)
        {
            //this.A_Name = txtA_Name.Text;
            //this.A_Manager = txtA_Manager.Text;
            Response.Redirect(searchURL);
        }

        #endregion

        #region 删除操作=================================

        //批量删除
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            //检查权限
            //ChkAdminLevel("user_list", ShareMarkingEnums.ActionEnum.Delete.ToString());

            int sucCount = 0;
            int errorCount = 0;
            for (int i = 0; i < rptList.Items.Count; i++)
            {
                int id = Convert.ToInt32(((HiddenField)rptList.Items[i].FindControl("hidId")).Value);
                CheckBox cb = (CheckBox)rptList.Items[i].FindControl("chkId");
                if (cb.Checked)
                {
                    if (qr_StoreService.Instance.Delete_Entity(qr_Store._.StoreCode == id))
                    {
                        sucCount += 1;
                    }
                    else
                    {
                        errorCount += 1;
                    }
                }
            }

            //记录日志
            AddAdminLog(DTEnums.ActionEnum.Delete.ToString(), "删除qr_Store" + sucCount + "条，失败" + errorCount + "条");

            JscriptMsg("删除成功" + sucCount + "条，失败" + errorCount + "条！", searchURL, "Success");
        }

        #endregion

        #region 导出成Excel表格==================

        protected void btnDownload_Click(object sender, EventArgs e)
        {
            int sucCount = 0;
            int errorCount = 0;
            try
            {
                DataSet ds = new DataSet();
                DataTable table = DbSession.Default.From<qr_Store>().Select(qr_Store._.S_Name, qr_Store._.S_Provinces, qr_Store._.S_City, qr_Store._.S_Area, qr_Store._.S_Region, qr_Store._.CreateOn).ToTable();
                table.TableName = "qr_Store";
                ds.Tables.Add(table);

                ExcelExportProvider provider = ExcelExportConfiguration.Current.ExcelConfigs["storeinfo"];

                // 导入配置文件验证
                ConfigExportValidate(provider, ds, "storeinfo");
                string fullPath;
                string templateFile = null;
                if (!string.IsNullOrEmpty(templateFile))
                    fullPath = templateFile;
                else if (!string.IsNullOrEmpty(provider.TemplateFile))
                {
                    HttpContext context = HttpContext.Current;
                    if (context != null)
                    {
                        fullPath = context.Server.MapPath("~/" + provider.TemplateFile);
                    }
                    else
                    {
                        fullPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, provider.TemplateFile);
                    }
                }
                else
                    throw new Exception("参数excelFile及预设的TemplateFile都为空，无法打开Excel文件");

                ExcelUtilities excelUtils = new ExcelUtilities();
                excelUtils.ExportExcel(Response, string.Format("ExportCode_{0}", DateTime.Now.ToString("yyyy-MM-dd")), ds, "storeinfo");
                sucCount += 1;
            }
            catch (Exception ex)
            {
                WriteLog.WriteError(ex.ToString());
                JscriptMsg("下载时发生错误请联系管理员！", searchURL, "Error");
            }
            //记录日志
            AddAdminLog(DTEnums.ActionEnum.Export.ToString(), "导出门店信息" + sucCount + "条，失败" + errorCount + "条");

            JscriptMsg("下载成功" + sucCount + "条，失败" + errorCount + "条！", searchURL, "Success");
        }

        protected void ConfigExportValidate(ExcelExportProvider provider, DataSet container, string typeName)
        {
            ///验证数据容器中是否存在DataTable
            if (container.Tables.Count == 0) throw new Exception("DataSet对象容器中没有任何DataTable对象!");
            ///验证导入配置中的配置节是否存在
            if (provider == null) throw new Exception(string.Format("配置中不存在类型为:{0}的导入配置项!", typeName));
            ///验证配置节中是否包含至少1个worksheet
            if (provider.Worksheets == null || provider.Worksheets.Count == 0) throw new Exception(string.Format("配置中类型为:{0}的配置节中不包含Worksheet的定义", typeName));
            // 验证数据容器中存在配置节中配置的datatable
            foreach (var worksheet in provider.Worksheets)
            {
                foreach (Area area in worksheet.Areas)
                    if (!container.Tables.Contains(area.DataTable))
                        throw new Exception(string.Format("DataTable中不包含表 {0}", area.DataTable));
            }
        }
        #endregion

        #region 生成二维码
        public string GetQRCode(string StoreCode)
        {
            var relate = qr_QrCodeRelateService.Instance.Get_SingleEntity_byWhere(qr_QrCodeRelate._.qr_Type == "1002" &&
                qr_QrCodeRelate._.rel_Code == StoreCode);
            if (relate != null)
            {
                var qrcode = qr_QrCodeService.Instance.Get_SingleEntity_byWhere(qr_QrCode._.scene_id == relate.qr_Scene_ID);
                if (qrcode != null)
                    return qrcode.qrcode_url;
                return "";
            }
            return "";
        }
        #endregion

        protected void sync_click(object sender, EventArgs e)
        {
            Sync_QrCode();
        }

        #region 生成二维码
        public void Sync_QrCode()
        {
            //两个特殊的入口
            //var nclist = qr_StoreService.Instance.Get_Entity_byWhere(
            //    qr_Store._.StoreCode == "02LHCDL" || qr_Store._.StoreCode == "03LHfriend", null);

            //先得到所有的需要更新二维码的NC
            var nclist = qr_StoreService.Instance.Get_Entity_byWhere(qr_Store._.isneedupdate == true, null);

            nclist.ForEach(o =>
            {
                #region MyRegion

                var has = qr_QrCodeRelateService.Instance.Get_IsExist_ByWhere(
                    qr_QrCodeRelate._.qr_Type == 1002 && qr_QrCodeRelate._.IsDelete == false
                    && qr_QrCodeRelate._.rel_Code == o.StoreCode);

                if (!has)
                {
                    #region 如果在关联表没有NC对应的记录，就新增二维码

                    //查询是否有以前弃用的二维码
                    var oldqr = qr_QrCodeService.Instance.Get_Entitys_ByTop(1, qr_QrCode._.type == 1002 &&
                        qr_QrCode._.isdelete == true, qr_QrCode._.scene_id.Asc);

                    if (oldqr.IsNullOrCountLTE0())
                    {
                        #region get sceneid
                        var sceneid = 0;
                        qr_QrCodeType type = qr_QrCodeTypeService.Instance.Get_SingleEntity_byWhere(qr_QrCodeType._.QrCodeTypeID == 1002);
                        sceneid = type.QT_CurrentIndex.ConvertTo<int>() + 1;
                        #endregion

                        #region 编辑图文信息
                        var extra = new List<extra>() { 
                                new extra { 
                                    title="美赞臣蓝臻，突破性贴近宝宝需求，新妈买一赠一限量臻享",
                                    shortdesc="",
                                    linkurl="http://wx.ismartgo.com/app/lighthouse/index.aspx?from="+o.StoreCode+"$type=2$openid=####",
                                    picurl="http://qrcode.mjn.howjoin.com/imgforweixin/activity.jpg"
                                }
                            };
                        var message = new message()
                        {
                            title = o.StoreCode + "的二维码",
                            remark = o.StoreCode + "的二维码",
                            sacode = "test",
                            scene_id = sceneid.ToString(),
                            extra = extra
                        };
                        #endregion

                        #region 请求vigo 生成二维码
                        var vigo = new Qrcode_vigo(this.httpstr, this.signsecret);
                        var resultentity = vigo.CreateQrcode(message);
                        #endregion

                        while (resultentity.errcode == "10")
                        {
                            ComLib.LogLib.Log4NetBase.Log("二维码sceneid重复" + sceneid);
                            sceneid += 1;
                            message.scene_id = sceneid.ToString();
                            resultentity = vigo.CreateQrcode(message);
                        }

                        #region 将返回的信息保存
                        if (resultentity.errcode == "00")
                        {
                            #region 保存二维码
                            qr_QrCode qrcode = new qr_QrCode()
                            {
                                id = resultentity.message.id,
                                type = 1002,
                                scene_id = resultentity.message.scene_id,
                                sacode = resultentity.message.sacode,
                                title = resultentity.message.title,
                                remark = resultentity.message.remark,
                                code_url = resultentity.message.code_url,
                                qrcode_url = resultentity.message.qrcode_url,
                                addtime = resultentity.message.addtime,
                                status = resultentity.message.status,
                                DateModified = DateTime.Now,
                                wx_title = "美赞臣蓝臻，突破性贴近宝宝需求，新妈买一赠一限量臻享",
                                wx_content = "",
                                wx_url = "http://wx.ismartgo.com/app/lighthouse/index.aspx?from=" + o.StoreCode + "$openid=####",
                                wx_imgurl = "http://qrcode.mjn.howjoin.com/imgforweixin/activity.jpg",
                                isdelete = false
                            };
                            qr_QrCodeService.Instance.Add_Entity(qrcode);
                            #endregion

                            #region 添加关联
                            qr_QrCodeRelate qrrelate = new qr_QrCodeRelate()
                            {
                                qr_Type = 1002,//1002是门店
                                qr_CodeID = resultentity.message.id,
                                qr_Scene_ID = resultentity.message.scene_id,
                                rel_Code = o.StoreCode,
                                IsDelete = false,
                                CreateOn = DateTime.Now
                            };
                            qr_QrCodeRelateService.Instance.Add_Entity(qrrelate);
                            #endregion

                            #region 更改二维码类型表
                            type.QT_CurrentIndex = sceneid;
                            type.QT_Used = type.QT_Used + 1;
                            type.QT_Surplus = type.QT_Surplus - 1;
                            qr_QrCodeTypeService.Instance.Update_Entity(type);
                            #endregion
                        }
                        #endregion

                        ComLib.LogLib.Log4NetBase.Log("3、====更新门店二维码========新增===门店编号:" + o.StoreCode + "::==sceneid==" + resultentity.message.scene_id);
                    }
                    else
                    {
                        #region 更新
                        var qr = oldqr[0];

                        #region 更新二维码

                        #region 编辑图文信息
                        var extra = new List<extra>() { 
                                new extra { 
                                    title="美赞臣蓝臻，突破性贴近宝宝需求，新妈买一赠一限量臻享",
                                    shortdesc="",
                                    linkurl="http://wx.ismartgo.com/app/lighthouse/index.aspx?from="+o.StoreCode+"$type=2$openid=####",
                                    picurl="http://qrcode.mjn.howjoin.com/imgforweixin/activity.jpg"
                                }
                            };
                        var message = new message2()
                        {
                            id = qr.id.ToString(),
                            title = o.S_Name,
                            remark = o.S_Name + "的二维码",
                            sacode = "test",
                            extra = extra
                        };
                        #endregion

                        #region 请求vigo 生成二维码
                        var vigo = new Qrcode_vigo(this.httpstr, this.signsecret);
                        var resultentity = vigo.UpdateQrcode(message);
                        #endregion
                        #endregion

                        #region 新建关联
                        qr_QrCodeRelate qrrelate = new qr_QrCodeRelate()
                        {
                            qr_Type = 1002,//1是NC
                            qr_CodeID = qr.id,
                            qr_Scene_ID = qr.scene_id,
                            rel_Code = o.StoreCode,
                            IsDelete = false,
                            CreateOn = DateTime.Now
                        };
                        qr_QrCodeRelateService.Instance.Add_Entity(qrrelate);
                        #endregion

                        ComLib.LogLib.Log4NetBase.Log("Store，使用旧的二维码：：：NCCode：：" + o.StoreCode + "::==sceneid==::" + qrrelate.qr_Scene_ID);
                        #endregion
                    }
                    #endregion
                }
                else
                {
                    #region 如果有了二维码，也更新一次
                    var relate = qr_QrCodeRelateService.Instance.Get_SingleEntity_byWhere(
                    qr_QrCodeRelate._.qr_Type == 1002 && qr_QrCodeRelate._.IsDelete == false
                    && qr_QrCodeRelate._.rel_Code == o.StoreCode);

                    if (relate != null)
                    {
                        var qrcode = qr_QrCodeService.Instance.Get_SingleEntity_byWhere(qr_QrCode._.id == relate.qr_CodeID);
                        if (qrcode != null)
                        {
                            #region 更新二维码

                            #region 编辑图文信息
                            var extra = new List<extra>() { 
                                new extra { 
                                    title="美赞臣蓝臻，突破性贴近宝宝需求，新妈买一赠一限量臻享",
                                    shortdesc="",
                                    linkurl="http://wx.ismartgo.com/app/lighthouse/index.aspx?from="+o.StoreCode+"$type=2$openid=####",
                                    picurl="http://qrcode.mjn.howjoin.com/imgforweixin/activity.jpg"
                                }
                            };
                            var message = new message2()
                            {
                                id = qrcode.id.ToString(),
                                title = o.StoreCode,
                                remark = o.StoreCode + "的二维码",
                                sacode = "test",
                                extra = extra
                            };
                            #endregion

                            #region 请求vigo 生成二维码
                            var vigo = new Qrcode_vigo(this.httpstr, this.signsecret);
                            var resultentity = vigo.UpdateQrcode(message);
                            #endregion
                            #endregion

                            ComLib.LogLib.Log4NetBase.Log("Store二维码修改：：：NCCode：：" + o.StoreCode + "::==sceneid==::" + relate.qr_Scene_ID);
                        }
                    }
                    #endregion
                }
                #endregion

                o.isneedupdate = false;
                qr_StoreService.Instance.Update_Entity(o);
            });
        }
        #endregion

        protected void exportIMG_Click(object sender, EventArgs e)
        {
            //var nclist = qr_StoreService.Instance.Get_Entity_byWhere(qr_Store._.StoreCode == "20269405" || qr_Store._.StoreCode == "20607840", null);
            var nclist = qr_StoreService.Instance.Get_Entity_byWhere(
                qr_Store._.isneedupload == true, null);
            nclist.ForEach(o =>
            {
                var entity = qr_QrCodeRelateService.Instance.Get_SingleEntity_byWhere(
                    qr_QrCodeRelate._.qr_Type == 1002 && qr_QrCodeRelate._.IsDelete == false
                    && qr_QrCodeRelate._.rel_Code == o.StoreCode);
                if (entity != null)
                {
                    WebClient my = new WebClient();
                    
                    var qrcode = qr_QrCodeService.Instance.Get_SingleEntity_byWhere(qr_QrCode._.id == entity.qr_CodeID);
                    if (qrcode != null)
                    {
                        try
                        {
                            byte[] mybyte;
                            mybyte = my.DownloadData(qrcode.qrcode_url);
                            MemoryStream ms = new MemoryStream(mybyte);
                            System.Drawing.Image img;
                            img = System.Drawing.Image.FromStream(ms);
                            var path = System.Web.HttpContext.Current.Request.MapPath("/upload/storeimg/");
                            img.Save(path
                                + o.StoreCode + "-"
                                + o.S_Name.Replace("?", "").Replace("？", "").Replace("<", "").Replace(">", "").Replace("/","") + ".png",
                                ImageFormat.Png);   //保存
                            //下面直接输出
                            //Response.ClearContent();
                            //Response.ContentType = "image/gif";
                            //Response.BinaryWrite(mybyte);

                            //已下载
                            o.isneedupload = false;
                            qr_StoreService.Instance.Update_Entity(o);
                        }
                        catch (Exception ex)
                        {
                            ComLib.LogLib.Log4NetBase.Log(o.StoreCode + "错误" + ex.Message);
                        }
                    }
                }
            });
        }
    }
}